package com.lxr0860.lxr0860production_test.itemactivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.GnssStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.Window;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.lxr0860.lxr0860production_test.R;
import com.lxr0860.lxr0860production_test.utils.Contants;
import com.lxr0860.lxr0860production_test.view.MyViewOld;

import java.util.ArrayList;
import java.util.List;

/**
 * 后续按老化测试里面的修改定位流程
 */
public class GPSActivity extends Activity {
    private TextView mTvLoctionInfo;
    private TextView mTvSatelliteInfo;
    private TextView mTvTimeInfo;
    private TextView tvCountInUse;
    private TextView tvleftTime;
    private MyViewOld mMvSignalInfo;
    private LocationManager mLocationManager;
    private static final String TAG = "GPS";
    private int gpsTimeout;
    private boolean firstLocate, locateSuccess;
    private int countInUse = 0;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Contants.DIALOG_POSITIVE:
                    Intent mIntent=new Intent();
                    Bundle bundle=new Bundle();
                    bundle.putBoolean("result",true);
                    mIntent.putExtras(bundle);
                    GPSActivity.this.setResult(Contants.TEST_ITEM_GPS,mIntent);
                    finish();
                    break;
                case Contants.DIALOG_NEGATIVE:
                    finish();
                    break;
            }
        }
    };

    private static final int GPS_TEST_COUNT = 1;
    private int gpsSuccessCount, gpsFailCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_gpslast);
        initView();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //程序退出，移除监听
        handler.removeCallbacks(gpsRepeatRunnable);
//        mLocationManager.removeUpdates(mLocationListener);
//        mLocationManager.removeGpsStatusListener(mStatusListener);
        openOrCloseGps(false);
    }


    private void initView() {
        mTvLoctionInfo = (TextView) findViewById(R.id.tvResult);
        mTvSatelliteInfo = (TextView) findViewById(R.id.tvCounts);
        tvCountInUse = (TextView) findViewById(R.id.tvCountInUse);
        mTvTimeInfo = (TextView) findViewById(R.id.tvUsedTime);
        mMvSignalInfo = (MyViewOld) this.findViewById(R.id.myView);
        tvleftTime = (TextView) findViewById(R.id.tv90Time);
    }


    @SuppressLint("MissingPermission")
    private void initData() {
        mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            mLocationManager.registerGnssStatusCallback(mStatusListener);
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,
                    0, mLocationListener);
        } else {
            openOrCloseGps(true);
        }
    }

    @SuppressLint("MissingPermission")
    private void openOrCloseGps(boolean enable) {
        if (enable) {
//                    mTvTimeInfo.setText("定位耗时:");
            //打开GPS
//            if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            try {
                mTvLoctionInfo.setText("定位启动");
                Settings.Secure.setLocationProviderEnabled(GPSActivity.this.
                        getContentResolver(), LocationManager.GPS_PROVIDER, true);
                mLocationManager.registerGnssStatusCallback(mStatusListener);
                mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,
                        0, mLocationListener);
            } catch (Exception e) {
                e.printStackTrace();
            }
//            }
        } else {
            //关闭GPS
//            if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            try {
                mLocationManager.removeUpdates(mLocationListener);
                mLocationManager.unregisterGnssStatusCallback(mStatusListener);
                Settings.Secure.setLocationProviderEnabled(GPSActivity.this.
                        getContentResolver(), LocationManager.GPS_PROVIDER, false);
                Log.e("cly","closeGPS");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        }
    }

    /**
     * GPS定位监听
     */
    private LocationListener mLocationListener = new LocationListener() {
        //GPS状态变化时触发
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
                //GPS状态为可见时
                case LocationProvider.AVAILABLE:
//                    Log.e(TAG, "当前GPS状态为可见状态");
                    break;
                //GPS状态为服务区外时
                case LocationProvider.OUT_OF_SERVICE:
//                    Log.e(TAG, "当前GPS状态为服务区外状态");
                    break;
                //GPS状态为暂停服务时
                case LocationProvider.TEMPORARILY_UNAVAILABLE:
//                    Log.e(TAG, "当前GPS状态为暂停服务状态");
                    break;
            }
        }

        //GPS开启时触发
        @Override
        public void onProviderEnabled(String provider) {
            Log.e(TAG, "onProviderEnabled");
        }

        //GPS禁用时触发
        @Override
        public void onProviderDisabled(String provider) {
            Log.e(TAG, "onProviderDisabled");
            firstLocate = false;
        }

        //位置信息变化时触发
        @Override
        public void onLocationChanged(Location location) {
            Log.e(TAG, "onLocationChanged");
            if (firstLocate) {
                locateSuccess = true;
                Log.e("cly", "定位成功");
                handler.removeCallbacks(gpsRepeatRunnable);
//                handler.removeCallbacks(gpsRunnable);
                updateView(location);
            } else {
                Log.e("cly", "首次清除星历");
                mLocationManager.sendExtraCommand(
                        LocationManager.GPS_PROVIDER,
                        "delete_aiding_data", null);
                mTvTimeInfo.setText("清除星历信息成功");
                gpsTimeout = 0;
                handler.postDelayed(gpsRepeatRunnable, 1000);
//                handler.postDelayed(gpsRunnable,1000);
            }
        }
    };


    /**
     * GPS状态监听
     */

    private GnssStatus.Callback mStatusListener = new GnssStatus.Callback() {
        @Override
        public void onStarted() {
            super.onStarted();
            Log.e(TAG, "第一次定位");
            Log.e(TAG, "GPS_EVENT_STARTED");
        }

        @Override
        public void onStopped() {
            super.onStopped();
            Log.e(TAG, "GPS_EVENT_STOPPED");
            mLocationManager.removeUpdates(mLocationListener);
        }

        @Override
        public void onFirstFix(int ttffMillis) {
            super.onFirstFix(ttffMillis);
            Log.e(TAG, "第一次定位");
            firstLocate = true;
        }

        @Override
        public void onSatelliteStatusChanged(@NonNull GnssStatus status) {
            super.onSatelliteStatusChanged(status);
            //获取当前状态
//            @SuppressLint("MissingPermission") GpsStatus gpsStatus = mLocationManager.get(null);
            //获取卫星颗数的默认最大值
            int maxSatellites = status.getSatelliteCount();

            List<Float> mSnrf = new ArrayList<>();
            List<String> indexs = new ArrayList<>();
            int usedCount = 0;//有效卫星个数
            for (int i = 0; i < maxSatellites; i++) {
                float cn0DbHz = status.getCn0DbHz(i);
                int svid = status.getSvid(i);
                if (cn0DbHz > -1.0 && mSnrf.size() < 20) {
                    mSnrf.add(cn0DbHz);//信号强度
                    indexs.add(String.valueOf(svid));
                }
                if (status.usedInFix(i) & locateSuccess) {
                    tvCountInUse.append(svid
                            + "号有效卫星信号强度：" + cn0DbHz + "\n");
                    usedCount++;
                    Log.e("SNR：", svid
                            + "号有效卫星信号强度：" + cn0DbHz);
                }
            }
            mTvSatelliteInfo.setText("卫星总个数:" + maxSatellites + ",有效个数:" + usedCount);
            float[] mSnrfResult = new float[16];
            for (int i = 0; i < mSnrf.size(); i++) {
                if (i < 16) {
                    mSnrfResult[i] = mSnrf.get(i).floatValue();
                } else {
                    break;
                }
            }
            String[] mStrPrns = indexs.toArray(new String[maxSatellites]);
            if (maxSatellites != 0) {
                mMvSignalInfo.setProgress(mSnrfResult, mStrPrns);
            }
            //定位启动
        }
    };

    /**
     * 更新位置信息
     *
     * @param location
     */
    private void updateView(Location location) {
        if (location != null) {
            mTvLoctionInfo.setTextColor(Color.parseColor("#EE7600"));
            Log.e("cly", "lng=" + location.getLongitude() + "--lat=" + location.getLatitude());
            mTvLoctionInfo.setText("经度：" + location.getLongitude()
                    + "\r\n纬度：" + location.getLatitude());
            if (gpsTimeout <= 60) {
                gpsSuccessCount++;
                mTvTimeInfo.setText("第" + (gpsFailCount + gpsSuccessCount)
                        + "次定位成功：" + gpsTimeout + "秒");
                handler.removeCallbacks(gpsRepeatRunnable);
                if (!gpsTestOver()) {
                    mLocationManager.sendExtraCommand(
                            LocationManager.GPS_PROVIDER,
                            "delete_aiding_data", null);
                    tvCountInUse.setText("");
                    Log.e("cly", "清除星历");
                    gpsTimeout = 0;
                    handler.postDelayed(gpsRepeatRunnable, 1000);
                }
            }
        }
    }


    Runnable gpsRepeatRunnable = new Runnable() {
        @Override
        public void run() {
            gpsTimeout++;
            handler.postDelayed(this, 1000);
            if (gpsTimeout > 120) {
                gpsFailCount++;
                mTvTimeInfo.setText("第" + (gpsFailCount + gpsSuccessCount)
                        + "次定位超时：" + gpsTimeout + "秒");
                handler.removeCallbacks(gpsRepeatRunnable);
                if (!gpsTestOver()) {
                    mLocationManager.sendExtraCommand(
                            LocationManager.GPS_PROVIDER,
                            "delete_aiding_data", null);
                    tvCountInUse.setText("");
                    gpsTimeout = 0;
                    handler.postDelayed(gpsRepeatRunnable, 1000);
                }
            } else {
                tvleftTime.setText("所用时间：" + gpsTimeout + "S");
            }
        }
    };


    private boolean gpsTestOver() {
        if ((gpsFailCount + gpsSuccessCount) == GPS_TEST_COUNT) {
            tvCountInUse.setText("");
            handler.removeCallbacks(gpsRepeatRunnable);
            openOrCloseGps(false);
            mTvTimeInfo.setText("测试结束(失败：" + gpsFailCount
                    + "次|成功：" + gpsSuccessCount + "次)");
            if (gpsSuccessCount==GPS_TEST_COUNT){
                Contants.showDailog(GPSActivity.this,"定位成功，是否保存此次测试",handler, Gravity.TOP);
            }
            return true;
        } else {
            return false;
        }
    }

}